<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="归属部门" prop="deptId">
        <el-cascader 
          v-model="queryParams.deptId"
          :options="enabledDeptOptions" 
          :props="cascaderProps"
          :show-all-levels="false"
          clearable
          placeholder="请选择归属部门"
          @change="handleDeptChange"
        ></el-cascader>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['demo:history:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['demo:history:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['demo:history:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['demo:history:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="historyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="归属部门" align="center" prop="deptName" />
      <el-table-column label="购买顾客" align="center" prop="name" />
      <el-table-column label="购买内容" align="center" prop="purchaseContent">
        <template slot-scope="scope">
          <div v-if="scope.row.enhancedPurchaseContent && scope.row.enhancedPurchaseContent.length > 0">
            <el-tag 
              v-for="(item, index) in scope.row.enhancedPurchaseContent" 
              :key="index"
              size="small"
              style="margin: 2px;"
            >
              {{ item.purchaseType === '0' ? item.comboName : item.productName }} x {{ item.purchaseNum }}
            </el-tag>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="原价" align="center" prop="price" />
      <el-table-column label="成交价" align="center" prop="transactionPrice" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['demo:history:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['demo:history:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改购买记录抽屉 -->
    <el-drawer
      :title="title"
      :visible.sync="open"
      direction="rtl"
      size="70%"
      :before-close="cancel"
    >
      <div class="drawer-content">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-divider content-position="left">基本信息</el-divider>
          
          <el-form-item label="顾客昵称" prop="openId">
            <el-select v-model="form.openId" placeholder="请选择顾客昵称" style="width: 100%">
              <el-option
                v-for="item in customerList"
                :key="item.openId"
                :label="item.name"
                :value="item.openId"
              ></el-option>
            </el-select>
          </el-form-item>
          
          <el-divider content-position="left">购买内容</el-divider>
          
          <el-form-item label="购买内容" prop="purchaseContentArray">
            <div class="purchase-content-container">
              <el-button 
                type="primary" 
                icon="el-icon-plus" 
                size="mini" 
                @click="addPurchaseItem"
                style="margin-bottom: 10px;"
              >
                添加购买项
              </el-button>
              
              <el-table 
                :data="form.purchaseContentArray" 
                border 
                size="mini"
                style="width: 100%"
                v-if="form.purchaseContentArray && form.purchaseContentArray.length > 0"
              >
                <el-table-column label="购买类型" :min-width="120">
                  <template slot-scope="scope">
                    <el-select 
                      v-model="scope.row.purchaseType" 
                      placeholder="请选择" 
                      size="mini"
                      @change="handlePurchaseTypeChange(scope.row)"
                    >
                      <el-option 
                        v-for="dict in dict.type.purchase_type"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      ></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                
                <el-table-column label="套餐名称" :min-width="180" v-if="form.purchaseContentArray.some(item => item.purchaseType === '0')">
                  <template slot-scope="scope">
                    <el-select
                      v-model="scope.row.comboId"
                      placeholder="请选择套餐"
                      size="mini"
                      style="width: 100%"
                      v-if="scope.row.purchaseType === '0'"
                      @change="handleComboChange(scope.row, $event)"
                    >
                      <el-option
                        v-for="combo in comboList"
                        :key="combo.id"
                        :label="combo.name"
                        :value="combo.id"
                      ></el-option>
                    </el-select>
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                
                <el-table-column label="单品名称" :min-width="180" v-if="form.purchaseContentArray.some(item => item.purchaseType === '1')">
                  <template slot-scope="scope">
                    <el-select
                      v-model="scope.row.productId"
                      placeholder="请选择单品"
                      size="mini"
                      style="width: 100%"
                      v-if="scope.row.purchaseType === '1'"
                      @change="handleProductChange(scope.row, $event)"
                    >
                      <el-option
                        v-for="product in productList"
                        :key="product.id"
                        :label="product.name"
                        :value="product.id"
                      ></el-option>
                    </el-select>
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                
                <el-table-column label="购买数量" :min-width="140">
                  <template slot-scope="scope">
                    <el-input-number 
                      v-model="scope.row.purchaseNum" 
                      :min="1" 
                      controls-position="right"
                      size="mini"
                    ></el-input-number>
                  </template>
                </el-table-column>
                
                <el-table-column label="操作" width="80">
                  <template slot-scope="scope">
                    <el-button 
                      type="text" 
                      size="mini" 
                      icon="el-icon-delete" 
                      @click="removePurchaseItem(scope.$index)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              
              <div v-else class="empty-purchase-content">
                <span>暂无购买内容，请点击上方按钮添加</span>
              </div>
            </div>
          </el-form-item>
          
          <el-divider content-position="left">价格信息</el-divider>
          
          <el-form-item label="原价" prop="price">
            <el-input-number 
              v-model="form.price" 
              controls-position="right" 
              :precision="2" 
              :min="0" 
              style="width: 100%"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="成交价" prop="transactionPrice">
            <el-input-number 
              v-model="form.transactionPrice" 
              controls-position="right" 
              :precision="2" 
              :min="0" 
              style="width: 100%"
            ></el-input-number>
          </el-form-item>
        </el-form>
        
        <div class="drawer-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { listHistory, getHistory, delHistory, addHistory, updateHistory } from "@/api/demo/history";
import { getAllList } from "@/api/demo/customer";
import { listCombo } from "@/api/demo/combo";
import { listProduct } from "@/api/demo/product";
import { deptTreeSelect } from "@/api/system/user";

export default {
  name: "History",
  dicts: ["purchase_type"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 购买记录表格数据
      historyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        openId: null,
        purchaseContent: null,
        price: null,
        transactionPrice: null,
      },
      // 表单参数
      form: {
        purchaseContentArray: [] // 用于前端编辑的购买内容数组
      },
      // 表单校验
      rules: {
        openId: [
          { required: true, message: "顾客不能为空", trigger: "change" }
        ],
        purchaseContentArray: [
          { 
            validator: (rule, value, callback) => {
              if (!value || value.length === 0) {
                callback(new Error("至少添加一个购买项"));
              } else {
                // 检查每个购买项是否完整
                for (let i = 0; i < value.length; i++) {
                  const item = value[i];
                  if (!item.purchaseType) {
                    callback(new Error(`第${i+1}项购买类型不能为空`));
                    return;
                  }
                  if (item.purchaseType === '0' && !item.comboId) {
                    callback(new Error(`第${i+1}项套餐名称不能为空`));
                    return;
                  }
                  if (item.purchaseType === '1' && !item.productId) {
                    callback(new Error(`第${i+1}项单品名称不能为空`));
                    return;
                  }
                  if (!item.purchaseNum || item.purchaseNum < 1) {
                    callback(new Error(`第${i+1}项购买数量必须大于0`));
                    return;
                  }
                }
                callback();
              }
            }, 
            trigger: 'blur' 
          }
        ],
        price: [
          { required: true, message: "原价不能为空", trigger: "blur" }
        ],
        transactionPrice: [
          { required: true, message: "成交价不能为空", trigger: "blur" }
        ]
      },
      // 级联选择器配置
      cascaderProps: {
        value: 'id',
        label: 'label',
        children: 'children',
        checkStrictly: false, // 设置为true可选择任意一级，false只能选最后一级
        emitPath: false // 设置为false只返回最后一级的值，true返回完整路径
      },
      // 所有部门树选项
      deptOptions: undefined,
      // 过滤掉已禁用部门树选项
      enabledDeptOptions: undefined,
      customerList: [],
      // 套餐列表
      comboList: [],
      // 产品列表
      productList: [],
    };
  },
  async created() {
    // 先加载部门树、套餐列表和产品列表
    await this.getDeptTree();
    await this.getComboList();
    await this.getProductList();
    // 然后加载购买记录列表
    this.getList();
  },
  methods: {
    /** 获取所有套餐列表 */
    getComboList() {
      return new Promise((resolve) => {
        listCombo({pageNum:1,pageSize:1000}).then(response => {
          this.comboList = response.rows;
          resolve();
        }).catch(() => {
          this.comboList = [];
          resolve();
        });
      });
    },
    /** 获取所有产品列表 */
    getProductList() {
      return new Promise((resolve) => {
        listProduct({pageNum:1,pageSize:1000}).then(response => {
          this.productList = response.rows;
          resolve();
        }).catch(() => {
          this.productList = [];
          resolve();
        });
      });
    },
    /** 查询客户信息 */
    getCustomerList() {
      getAllList().then(response => {
        this.customerList = response.data;
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      return new Promise((resolve) => {
        deptTreeSelect().then(response => {
          this.deptOptions = response.data;
          this.enabledDeptOptions = this.filterDisabledDept(JSON.parse(JSON.stringify(response.data)));
          resolve();
        }).catch(() => {
          this.deptOptions = [];
          this.enabledDeptOptions = [];
          resolve();
        });
      });
    },
    // 过滤禁用的部门
    filterDisabledDept(deptList) {
      return deptList.filter(dept => {
        if (dept.disabled) {
          return false;
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children);
        }
        return true;
      });
    },
    // 部门选择变化处理
    handleDeptChange(value) {
      console.log('选中的部门ID:', value);
      // 由于设置了 emitPath: false，value 直接就是最后一级的部门ID
      this.queryParams.deptId = value;
    },
    /** 查询购买记录列表 */
    getList() {
      this.loading = true;
      // 确保传递的是最后一级部门ID
      const params = {
        ...this.queryParams,
        deptId: Array.isArray(this.queryParams.deptId) ? 
                this.queryParams.deptId[this.queryParams.deptId.length - 1] : 
                this.queryParams.deptId
      };
      
      listHistory(params).then(response => {
        // 处理购买内容，添加名称字段以便显示
        this.historyList = response.rows.map(item => {
          if (item.purchaseContent) {
            try {
              const purchaseContent = JSON.parse(item.purchaseContent);
              // 为每个购买项添加显示名称
              const enhancedContent = purchaseContent.map(purchaseItem => {
                if (purchaseItem.purchaseType === '0') {
                  const combo = this.comboList.find(c => c.id == purchaseItem.comboId);
                  return {
                    ...purchaseItem,
                    comboName: combo ? combo.name : '未知套餐'
                  };
                } else {
                  const product = this.productList.find(p => p.id == purchaseItem.productId);
                  return {
                    ...purchaseItem,
                    productName: product ? product.name : '未知单品'
                  };
                }
              });
              // 将增强后的内容存储到临时字段中，用于显示
              item.enhancedPurchaseContent = enhancedContent;
            } catch (e) {
              console.error('解析购买内容失败:', e);
              item.enhancedPurchaseContent = [];
            }
          } else {
            item.enhancedPurchaseContent = [];
          }
          return item;
        });
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deptId: null,
        openId: null,
        purchaseContent: null,
        purchaseContentArray: [], // 重置购买内容数组
        price: null,
        transactionPrice: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.deptId = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加购买记录";
      this.getCustomerList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getHistory(id).then(response => {
        this.form = response.data;
        // 解析购买内容JSON字符串为数组
        if (this.form.purchaseContent) {
          try {
            const purchaseContent = JSON.parse(this.form.purchaseContent);
            // 为每个购买项添加显示名称
            this.form.purchaseContentArray = purchaseContent.map(item => {
              if (item.purchaseType === '0') {
                const combo = this.comboList.find(c => c.id == item.comboId);
                return {
                  ...item,
                  comboName: combo ? combo.name : '未知套餐'
                };
              } else {
                const product = this.productList.find(p => p.id == item.productId);
                return {
                  ...item,
                  productName: product ? product.name : '未知单品'
                };
              }
            });
          } catch (e) {
            console.error('解析购买内容失败:', e);
            this.form.purchaseContentArray = [];
          }
        } else {
          this.form.purchaseContentArray = [];
        }
        this.open = true;
        this.title = "修改购买记录";
        this.getCustomerList();
      });
    },
    /** 添加购买项 */
    addPurchaseItem() {
      this.form.purchaseContentArray.push({
        purchaseType: '0', // 默认为套餐
        comboId: null,
        productId: null,
        purchaseNum: 1
      });
    },
    /** 移除购买项 */
    removePurchaseItem(index) {
      this.form.purchaseContentArray.splice(index, 1);
    },
    /** 购买类型变化处理 */
    handlePurchaseTypeChange(item) {
      // 切换类型时清空另一个类型的ID
      if (item.purchaseType === '0') {
        item.productId = null;
      } else {
        item.comboId = null;
      }
    },
    /** 套餐选择变化处理 */
    handleComboChange(item, comboId) {
      // 可以在这里添加其他逻辑，比如自动填充价格等
      console.log('选择的套餐ID:', comboId);
    },
    /** 产品选择变化处理 */
    handleProductChange(item, productId) {
      // 可以在这里添加其他逻辑，比如自动填充价格等
      console.log('选择的产品ID:', productId);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理部门ID，确保是最后一级部门ID
          const formData = {
            ...this.form,
            deptId: Array.isArray(this.form.deptId) ? 
                    this.form.deptId[this.form.deptId.length - 1] : 
                    this.form.deptId,
            // 将购买内容数组转换为JSON字符串
            purchaseContent: JSON.stringify(this.form.purchaseContentArray.map(item => {
              // 只保留必要的字段，移除前端添加的显示名称字段
              const { comboName, productName, ...cleanItem } = item;
              return cleanItem;
            }))
          };
          
          // 删除前端使用的临时数组，避免传递给后端
          delete formData.purchaseContentArray;
          
          if (this.form.id != null) {
            updateHistory(formData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHistory(formData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除购买记录编号为"' + ids + '"的数据项？').then(function() {
        return delHistory(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('demo/history/export', {
        ...this.queryParams
      }, `history_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.drawer-content {
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
  overflow-y: auto;
}

.drawer-footer {
  position: absolute;
  bottom: 20px;
  right: 20px;
}

.el-divider {
  margin: 30px 0 20px 0;
}

.el-form-item {
  margin-bottom: 20px;
}

.purchase-content-container {
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 10px;
}

.empty-purchase-content {
  text-align: center;
  color: #909399;
  padding: 20px 0;
}
</style>